import koa from "koa";
import bodyParser from "koa-bodyparser";
import dotenv from "dotenv";
import staticAssetsServer from "koa-static";
import path from "path";
import fse from "fs-extra";
import cors from "@koa/cors";

import { crossDomain } from "./utils/cross-domain";
import { registerRouter } from "./controller";
import { chalkERROR, chalkINFO, chalkSUCCESS, chalkWARN, emoji } from "./utils/chalkTip";
import { httpLoggerMiddleware, logger } from "./utils/logger";

const app = new koa();

// 加载 env 文件
dotenv.config();

const isProduction = process.env.NODE_ENV !== "development";

// 跨域
// app.use(crossDomain);
app.use(cors());

// 解析 body
app.use(bodyParser());

// 注册路由
registerRouter(app);

// 日志
app.use(httpLoggerMiddleware);

// 上传文件所属的静态资源服务器
if (process.env.UPLOAD_PATH) {
    const staticAssetsPath = path.resolve(__dirname, "../", process.env.UPLOAD_PATH);
    fse.ensureDirSync(staticAssetsPath);
    app.use(staticAssetsServer(staticAssetsPath));
}

new Promise((resolve, reject) => {
    const server = app.listen({ port: process.env.SERVER_PORT, hostname: process.env.SERVER_HOST }, () => {
        resolve("ok");
    });
    server.timeout = 20 * 1000;
})
    .then(() => {
        // 启动成功后提示信息：
        console.log();
        logger.debug(chalkWARN(`项目环境: ${process.env.NODE_ENV}`));
        logger.debug(chalkSUCCESS(`http服务启动成功！`));
        logger.debug(chalkSUCCESS(`静态资源服务启动成功！`));
        logger.debug(chalkWARN(`服务地址: ${process.env.SERVER_HOST}:${process.env.SERVER_PORT}`));
        // console.log(chalkWARN(`项目环境: ${process.env.NODE_ENV}`));
        // console.log(chalkSUCCESS(`http服务启动成功！`));
        // console.log(chalkSUCCESS(`静态资源服务启动成功！`));
        // console.log(chalkWARN(`服务地址: ${process.env.SERVER_HOST}:${process.env.SERVER_PORT}`));
        // console.log(chalkWARN(`项目名称: ${PROJECT_NAME}`));
        // console.log(chalkWARN(`mysql数据库: ${MYSQL_CONFIG.database}`));
    })
    .catch(err => {
        logger.debug(chalkERROR("项目启动失败！"));
        logger.debug(err);
        // console.log(chalkERROR("项目启动失败！"));
        // console.log(err);
    });
